package com.csx.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csx.common.constant.WareConstant;
import com.csx.common.utils.PageUtils;
import com.csx.common.utils.Query;
import com.csx.gulimall.ware.dao.PurchaseDao;
import com.csx.gulimall.ware.entity.PurchaseDetailEntity;
import com.csx.gulimall.ware.entity.PurchaseEntity;
import com.csx.gulimall.ware.entity.WareSkuEntity;
import com.csx.gulimall.ware.service.PurchaseDetailService;
import com.csx.gulimall.ware.service.PurchaseService;
import com.csx.gulimall.ware.service.WareSkuService;
import com.csx.gulimall.ware.vo.MergeVo;
import com.csx.gulimall.ware.vo.PurchaseDoneVo;
import com.csx.gulimall.ware.vo.PurchaseItemDoneVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
@AllArgsConstructor
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    private PurchaseDetailService purchaseDetailService;
    private WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {


        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseEntityId = mergeVo.getPurchaseId();
        if (mergeVo.getPurchaseId() == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            save(purchaseEntity);
            purchaseEntityId = purchaseEntity.getId();
        }

        PurchaseEntity entity = this.baseMapper.selectById(purchaseEntityId);
        if (entity.getStatus() <= WareConstant.PurchaseStatus.ASSIGNED.getCode()) {
            List<Long> items = mergeVo.getItems();

            Long finalPurchaseEntityId = purchaseEntityId;
            List<PurchaseDetailEntity> entityList = items.stream().map(item -> {
                PurchaseDetailEntity byId = purchaseDetailService.getById(item);
                PurchaseDetailEntity purchaseEntity = new PurchaseDetailEntity();
                if (byId.getStatus() <= WareConstant.PurchaseDetailStatus.ASSIGNED.getCode()) {
                    purchaseEntity.setId(item);
                    purchaseEntity.setPurchaseId(finalPurchaseEntityId);
                    purchaseEntity.setStatus(WareConstant.PurchaseDetailStatus.ASSIGNED.getCode());
                    return purchaseEntity;
                } else {
                    return null;
                }
            }).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(entityList) && entityList.get(0) != null) {
                purchaseDetailService.updateBatchById(entityList);
            }

            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseEntityId);
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.ASSIGNED.getCode());
            this.updateById(purchaseEntity);
        }
    }

    @Override
    public void received(List<Long> ids) {
        // 确认当前采购单 的状态是否为新建或已分配状态
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids)
                .and(w -> {
                    w.eq("status", WareConstant.PurchaseStatus.CREATED.getCode())
                            .or()
                            .eq("status", WareConstant.PurchaseStatus.ASSIGNED.getCode());
                });

        List<PurchaseEntity> purchaseEntityList = this.list(wrapper);

        List<PurchaseEntity> purchaseEntityStream = this.list(wrapper).stream()
                .peek(purchaseEntity -> {
                    purchaseEntity.setUpdateTime(new Date());
                    purchaseEntity.setStatus(
                            WareConstant.PurchaseStatus.RECEIVE.getCode());
                }).collect(Collectors.toList());

        //修改采购单的状态
        this.updateBatchById(purchaseEntityStream);

        List<Long> collect = purchaseEntityList.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
        // 修改采购项的状态
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseIds(collect);

        List<PurchaseDetailEntity> entityList = purchaseDetailEntities.stream()
                .peek(purchaseDetailEntity -> {
                    purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.BUYING.getCode());
                }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(entityList);
    }

    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 改变采购单状态
        Long id = doneVo.getId();
        // 改变采购项状态
        boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();

        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseStatus.HAS_ERROR.getCode()) {
                flag = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatus.HAS_ERROR.getCode());
            } else {
                // 添加库存
                detailEntity.setStatus(WareConstant.PurchaseDetailStatus.FINISH.getCode());
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(item.getItemId(), entity.getWareId(), entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        // 修改采购单
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag
                ? WareConstant.PurchaseStatus.FINISH.getCode()
                : WareConstant.PurchaseStatus.HAS_ERROR.getCode());
        this.updateById(purchaseEntity);
    }

}